#!/bin/sh
#chkconfig:2345 80 90
# Simple Redis init.d script conceived to work on Linux systems
# as it does use of the /proc filesystem.
#NOWDATA=`data '+%F %T %3N'`

REDIS_BIN_DIR=/Documents/PSM70-linux-run-Standalone/init/Redis_init/../../bin/RedisServer
REDIS_DATA_DIR=/Documents/PSM70-linux-run-Standalone/init/Redis_init/../../bin/RedisServer

EXEC=$REDIS_BIN_DIR/redis-server
CLIEXEC=$REDIS_BIN_DIR/redis-cli

PIDFILE=$REDIS_DATA_DIR/redis_${REDISPORT}.pid
CONF=$REDIS_BIN_DIR/redis.conf

REDISPORT=$(sed -n '/^port/p' ${CONF}|awk -F" " '{print $NF}')
# 读取端口，读不到就设置默认值6379
if test -z ${REDISPORT}
then
    REDISPORT=6379
fi

redispid=`ps -ef | grep "redis-server" | grep -v grep | awk -F" " '{print $2}'`
rediswc=`ps -ef | grep "redis-server" | grep -v grep | awk -F" " '{print $8}' | grep redis | grep -v grep | wc -l`

case "$1" in
    start)
        if [ -f $PIDFILE -a "${rediswc}" = "1" ]
        then
            echo "$PIDFILE exists, process is already running or crashed"
        elif [ -f $PIDFILE -a "${rediswc}" != "1" ] 
        then
            rm -rf  $PIDFILE
            echo "Redis is crashed and now ReStarting Redis server..."
            $EXEC $CONF &
        elif [ ! -f $PIDFILE -a "${rediswc}" = "1" ]
        then
            echo -e "\033[31m redis is running but PIDFILE is not find ,so you must have root privileges \033[0m"
            echo -e "\033[31m PIDFILE is $PIDFILE \033[0m"
            kill -9 $redispid
            echo "Redis is exist now Starting Redis server..."
            $EXEC $CONF &
        else
            echo "Starting Redis server..."
            $EXEC $CONF &                
        fi
        ;;
    stop)
        if [ ! -f $PIDFILE ]
        then
            echo "$PIDFILE does not exist, process is not running"
            echo "now kill -9 $redispid"
            kill -9 $redispid
        else
            PID=`cat $PIDFILE`
            echo "Stopping ..."
            $CLIEXEC -p $REDISPORT shutdown
            i=0
            while [ -x /proc/${PID} ]
            do
                echo "Waiting for Redis to shutdown ..."
                let 'i +=1'
                if [ $i = '3' ]
                then
                    echo "now kill -9 $redispid"
                    kill -9 $redispid
                    break
                fi
                sleep 1
            done
            echo "Redis stopped"
        fi
        ;;
    newstart)
        if [ -f $PIDFILE ]
        then
            rm -f $PIDFILE
        fi
            cd $REDIS_BIN_DIR
        echo "Starting Redis server..."
        $EXEC $CONF &
        ;;
    *)
        echo "Please use start or stop as first argument"
        ;;
esac
